import 'dart:developer';

import 'package:custom_media_player/app_audio_player.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:lottie/lottie.dart';
import 'package:xf_evaluate/manager/entity/xf_eval_entity.dart';
import 'package:xf_evaluate/manager/xf_eval_manager.dart';
import 'package:xf_evaluate/page/base_widget.dart';
import 'package:xf_evaluate/utils/toast_utils.dart';

import '../manager/entity/xf_eval_result_entity.dart';
import '../utils/eval_result_utils.dart';

/// 评测页面
class XFEvalPage extends BaseWidget {
  final XFEvalEntity evalEntity;

  const XFEvalPage(this.evalEntity, {super.key});

  @override
  BaseWidgetState<BaseWidget> getState() {
    return _XFEvalPageState();
  }
}

class _XFEvalPageState extends BaseWidgetState<XFEvalPage>
    with SingleTickerProviderStateMixin
    implements AppAudioPlayerListener {
  /// 是否已开始评测
  bool isStartEval = false;

  /// 评测完成
  bool isEvalEnd = false;

  /// 动画控制器
  AnimationController? _animationController;

  /// 是否播放评测完成开始评测
  bool _isPlayCompleteStartEval = false;

  List<TextSpan> list = [];

  XFEvalResultEntity? _entity;

  double _recordPercentage = 0;

  /// 是否正在连接中
  bool _isStartRecord = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(vsync: this);
    if (widget.evalEntity.isPlayVoice) {
      _isPlayCompleteStartEval = true;
      playContentVoice();
    }
    debugPrint('注册评测监听');
    XFEvalManager.instance.setEvalListener(evalListener);
    XFEvalManager.instance.setOnPlayback(onPlayback);
    AppAudioPlayer.instance.setPlayListener(this);
  }

  @override
  void dispose() {
    _animationController?.dispose();
    _animationController = null;
    super.dispose();
    XFEvalManager.instance.dispose();
  }

  void onPlayback(PlaybackDisposition position) {
    /// 录音播放回调
    _recordPercentage = position.duration.inMilliseconds == 0
        ? 0
        : position.position.inMilliseconds / position.duration.inMilliseconds;
    log('当前百分比 $_recordPercentage');
    if (_recordPercentage > 0.99) {
      _recordPercentage = 0;
    }
    setState(() {});
  }

  void evalListener(XFEvalResultEntity entity) {
    log('收到监听 ${entity.type}');
    switch (entity.type) {
      case XFEvalEventType.startRecord:

        /// 开始录音
        _isStartRecord = false;
        break;
      case XFEvalEventType.endRecord:

        /// 结束录音  可能会多次回调
        isStartEval = false;
        _isStartRecord = false;
        break;
      case XFEvalEventType.evalResult:
        _entity = entity;
        _isStartRecord = false;

        /// 评测结果
        isEvalEnd = true;
        isStartEval = false;
        list = EvalResultUtils.instance(entity: entity).getResultTextSpan(
          xx(48),
        );
        _animationController?.stop();
        playEvalResultAudio();
        break;
      case XFEvalEventType.timeout:
        _isStartRecord = false;

        /// 前置超时
        isStartEval = false;
        break;
      case XFEvalEventType.error:
        _isStartRecord = false;

        /// 错误情况
        isStartEval = false;
        endEval();

        if(entity.errorCode == 1002){
          ToastUtils.showShort('网络异常，请重试~');
        }

        break;
      default:
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvoked: (didPop) {
        if (!didPop) {
          AppAudioPlayer.instance.pause();
          Navigator.of(context).pop(_entity);
        }
      },
      child: Scaffold(
        // backgroundColor: const Color(0xff495166).withOpacity(0.7),
        backgroundColor: Colors.transparent,
        body: GestureDetector(
          onTap: () {
            AppAudioPlayer.instance.pause();
            Navigator.of(context).pop(_entity);
          },
          child: Container(
            color: Colors.transparent,
            width: sw(),
            height: sh(),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                GestureDetector(
                  onTap: () {},
                  child: Container(
                    width: sw(),
                    constraints: BoxConstraints(maxHeight: sh() * 0.8),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(xx(32)),
                        topRight: Radius.circular(xx(32)),
                      ),
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          constraints: BoxConstraints(
                            maxHeight: sh() * 0.4,
                          ),
                          child: LayoutBuilder(
                            builder: (BuildContext context,
                                BoxConstraints constraints) {
                              return SingleChildScrollView(
                                padding: EdgeInsets.only(
                                    top: yy(24), left: xx(24), right: xx(24)),
                                child: isEvalEnd
                                    ? Text.rich(TextSpan(children: list))
                                    : Text(
                                        widget.evalEntity.content,
                                        style: TextStyle(
                                            fontSize: xx(48),
                                            color: const Color(0xff495166)),
                                      ),
                              );
                            },
                          ),
                        ),
                        SizedBox(
                          height: yy(16),
                        ),
                        isEvalEnd
                            ? Center(
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: buildStarList(),
                                ),
                              )
                            : Lottie.asset(
                                controller: _animationController,
                                'packages/xf_evaluate/assets/eval_voice.json',
                                // 设置动画宽度
                                width: xx(702),
                                // 设置动画高度
                                height: yy(88),
                                onLoaded: (composition) {
                                  _animationController?.duration =
                                      composition.duration;
                                },
                              ),
                        SizedBox(
                          height: yy(16),
                        ),
                        _isStartRecord
                            ? Text(
                                "评测连接中…",
                                style: TextStyle(
                                    color: Colors.grey, fontSize: xx(40)),
                              )
                            : Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  GestureDetector(
                                    onTap: () {
                                      AppAudioPlayer.instance.pause();
                                      Navigator.of(context).pop(_entity);
                                    },
                                    child: Image.asset(
                                      'packages/xf_evaluate/assets/images/ui_eval_close.webp',
                                      width: xx(120),
                                      height: xx(120),
                                    ),
                                  ),
                                  SizedBox(
                                    width: xx(140),
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      if (isStartEval) {
                                        endEval();
                                      } else {
                                        startEval();
                                      }
                                    },
                                    child: Image.asset(
                                      isStartEval
                                          ? 'packages/xf_evaluate/assets/images/icon_eval_pause.webp'
                                          : 'packages/xf_evaluate/assets/images/icon_eval_start.webp',
                                      width: xx(120),
                                      height: xx(120),
                                      fit: BoxFit.contain,
                                    ),
                                  ),
                                  SizedBox(
                                    width: xx(140),
                                  ),
                                  Stack(
                                    alignment: Alignment.center,
                                    children: [
                                      SizedBox(
                                        width: xx(100),
                                        height: xx(100),
                                        child: CircularProgressIndicator(
                                          // backgroundColor: Colors.grey[200],
                                          valueColor:
                                              const AlwaysStoppedAnimation(
                                                  Colors.amber),
                                          value: _recordPercentage,
                                        ),
                                      ),
                                      Visibility(
                                        visible:
                                            widget.evalEntity.voice != null ||
                                                isEvalEnd,
                                        child: GestureDetector(
                                          onTap: () {
                                            if (isEvalEnd) {
                                              XFEvalManager.instance
                                                  .playRecord();
                                            } else {
                                              // XFEvalManager.instance.playRecord(
                                              //     url: widget.evalEntity.voice ?? "",
                                              //     codec: Codec.defaultCodec);
                                              if (isStartEval) {
                                                return;
                                              }
                                              playContentVoice();
                                            }
                                          },
                                          child: Image.asset(
                                            isEvalEnd
                                                ? 'packages/xf_evaluate/assets/images/icon_eval_play.webp'
                                                : 'packages/xf_evaluate/assets/images/ui_icon_play.webp',
                                            width: xx(104),
                                            height: xx(104),
                                          ),
                                        ),
                                      ),
                                    ],
                                  )
                                ],
                              ),
                        SizedBox(
                          height: yy(28),
                        ),
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建评星
  List<Widget> buildStarList() {
    List<Widget> starList = [];
    var countStar = 5;
    var scoreStar = EvalResultUtils.instance().getStarCount();
    for (int i = 0; i < countStar; i++) {
      if (scoreStar > i) {
        starList.add(Image.asset(
          "packages/xf_evaluate/assets/images/ui_icon_start_3.webp",
          width: xx(88),
          height: xx(88),
        ));
      } else {
        starList.add(Image.asset(
          "packages/xf_evaluate/assets/images/ui_icon_start_4.webp",
          width: xx(88),
          height: xx(88),
        ));
      }
      starList.add(SizedBox(
        width: xx(16),
      ));
    }

    return starList;
  }

  /// 播放内容语音
  void playContentVoice() {
    if (widget.evalEntity.startAt == null || widget.evalEntity.endAt == null) {
      AppAudioPlayer.instance.play(widget.evalEntity.voice ?? '');
      return;
    }
    AppAudioPlayer.instance.play(
      widget.evalEntity.voice ?? "",
      startAt: Duration(
          milliseconds: ((widget.evalEntity.startAt ?? 0) * 1000).toInt()),
      endAt: Duration(
          milliseconds: ((widget.evalEntity.endAt ?? 0) * 1000).toInt()),
    );
  }

  /// 启动动画
  void startAnimation() {
    _animationController?.repeat();
  }

  /// 停止动画
  void stopAnimation() {
    _animationController?.stop();
  }

  /// 开始评测
  void startEval() async {
    isEvalEnd = false;
    if (isStartEval) {
      return;
    }
    AppAudioPlayer.instance.pause();
    await XFEvalManager.instance.stopPlayer();
    startAnimation();
    isStartEval = true;
    setState(() {});
    XFEvalManager.instance.startEval(widget.evalEntity);
  }

  /// 结束评测
  void endEval() {
    isStartEval = false;
    stopAnimation();
    setState(() {});
    XFEvalManager.instance.stopRecord();
  }

  /// 播放评测结果对应分数音效
  void playEvalResultAudio() async {
    String path = EvalResultUtils.instance().getAudioName();
    log('播放评测对应结束对应音频 $path');
    var data =
        (await rootBundle.load('packages/xf_evaluate/assets/audios/$path'))
            .buffer
            .asUint8List();
    XFEvalManager.instance.player.openPlayer().then((value) {
      value?.startPlayer(
          fromDataBuffer: data, codec: Codec.defaultCodec, whenFinished: () {});
    });
  }

  @override
  void onComplete() {
    if (_isPlayCompleteStartEval) {
      _isPlayCompleteStartEval = false;
      startEval();
    }
  }

  @override
  void onError({String? msg}) {}

  @override
  void onPause() {}

  @override
  void onPlay() {}

  @override
  void onProgress(Duration duration) {}

  @override
  void repeatReadReset() {}
}
